package br.com.montezuma.despesas.controller;

import java.util.ArrayList;
import java.util.List;

import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.ValidationMessage;
import br.com.montezuma.despesas.backend.CargoDAO;
import br.com.montezuma.despesas.models.Cargo;
import br.com.montezuma.despesas.utils.Container;
import br.com.montezuma.despesas.utils.Util;

/**
 * <pre>
 * @author : David Montezuma          
 * Purpose      :  CargoController, providing operations for Cargo.
 * Amendment History                                                                
 * Date - Name - Description                              
 * 20/05/2012 - David Montezuma - initial version.
 * 
 * Copyright 2012 Montezuma Software
 * </pre>
 */
@Resource
public class CargoController {

	private CargoDAO cargoDAO;
	private Result result;
	private Validator validator;

	public CargoController(Result result, CargoDAO cargoDAO, Validator validator) {
		this.cargoDAO = cargoDAO;
		this.result = result;
		this.validator = validator;
	}

	public List<Cargo> listar() {
		this.cargoDAO.open();
		List<Cargo> lista = this.cargoDAO.findAll();
		this.cargoDAO.close();
		return lista;
	}

	public void salvar(Cargo cargo) {
		if (Util.isEmpty(cargo.getNome())) {
			validator.add(new ValidationMessage(
					"Cargo nome deve ser informado", "cargo.nome"));
		}
		if (validator.getErrors().size() == 0) {
			this.cargoDAO.open();
			this.cargoDAO.beginTransaction();
			this.cargoDAO.save(cargo);
			this.cargoDAO.commitTransaction();
			this.cargoDAO.close();
			this.result.redirectTo(CargoController.class).listarEditar(null);
		}else{
			validator.onErrorUsePageOf(CargoController.class).listarEditar(null);
		}
	}

	public void editar() {

	}

	public Container<Cargo> listarEditar(Long id) {
		this.cargoDAO.open();
		Cargo editing = null;
		if (id != null) {
			editing = this.cargoDAO.findById(id);
		}
		List<Cargo> lista = this.cargoDAO.findAll();
		this.cargoDAO.close();
		Container<Cargo> c2 = new Container<Cargo>(lista, editing);
		return c2;

	}

	public void excluir(Long id) {
		if (id != null) {
			this.cargoDAO.open();
			this.cargoDAO.beginTransaction();
			this.cargoDAO.delete(this.cargoDAO.findById(id));
			this.cargoDAO.commitTransaction();
		}
		this.result.redirectTo(CargoController.class).listarEditar(null);
	}
}
